<?php
declare (strict_types=1);

namespace app\api\controller;


use Alipay\EasySDK\Kernel\Factory;
use app\common\facade\OssBackup;
use app\common\model\Area;
use app\common\model\Statistics;
use app\common\tool\pay\Pay;
use app\common\tool\pay\PayPreset;
use app\common\model\Logs;
use app\common\model\Order;
use app\common\model\User;
use app\common\tool\Result;

class Callback
{

    /**
     * @return void
     * 自动备份
     */
    public function autoOssBackup()
    {
        try {
            $route = 'callback/autoOssBackup.log';
            $result = OssBackup::auto();
            Logs::write($route, json_encode($result));
        } catch (\Exception $e) {
            Logs::write($route, $e->getMessage());
        }
    }

    /**
     * @return void
     * 更新统计
     */
    public function statistics()
    {
        Statistics::_timing();
    }


    public function product_save()
    {
        $route = 'callback/product_save.log';
        try {
            $param = request()->post();

            if(isset($param['province_name']) && $param['province_name']){
                $province = Area::whereLike('province','%'.$param['province_name'].'%')->field('code')->find();
                if(!$province){
                    Logs::write($route, '未查询到省份，请求数据：' . json_encode($param));
                    return Result::fail('未查询到省份');
                }
                $param['province'] = $province->code;
                unset($param['province_name']);
            }

            if(isset($param['city_name']) && $param['city_name']){
                $city = Area::whereLike('city', '%' . $param['city_name'] . '%')->field('code')->find();
                if(!$city){
                    Logs::write($route, '未查询到城市，请求数据：' . json_encode($param));
                    return Result::fail('未查询到城市');
                }
                $param['city'] = $city->code;
                unset($param['city_name']);
            }

            if(isset($param['county_name']) && $param['county_name'])
            {
                $district = Area::whereLike('district', '%' . $param['county_name'] . '%')->field('code')->find();
                if(!$district){
                    $param['district'] = $district->code;
                    unset($param['county_name']);
                }
            }

            \app\common\model\Product::create($param);
            return Result::success('success');
        } catch (\Exception $e) {
            Logs::write($route, $e->getMessage());
            return Result::fail($e->getMessage());
            // return ['code' => -1, 'msg' => $e->getMessage()];
        }
    }
    /**
     * @return string|void
     * 原点 2022年1月11日11:27:15 支付宝支付通用回调
     */
    public function aliPayOrder()
    {
        try {
            Factory::setOptions(Pay::getOptions(PayPreset::Instance()->getConfig()['alipay']));
            $route = 'callback/aliPayOrder.log';
            $param = $_POST;
            $result = Factory::payment()->common()->verifyNotify($param);
            if ($result) {
                if ($param['trade_status'] != 'TRADE_SUCCESS') {
                    Logs::write($route, '非支付回调');
                    exit();
                }
                $info = Order::get(['sn' => $param['out_trade_no']]);
                if ($info && $info->state == 1) {
                    $result = Order::operation($info, User::find($info['uid']), 'alipay');
                    if ($result['code'] == 1) {
                        Logs::write($route, '成功，订单号:' . $info->sn);
                    } else {
                        Logs::write($route, '失败，订单号:' . $info->sn . '->' . $result['msg']);
                    }
                } else {
                    Logs::write($route, '未查询到订单');
                }

                return 'success';
            } else {
                return 'fail';
            }
        } catch (\Exception $e) {
            return 'fail';
        }
    }



    public function RemitCallback()
    {
        try {
            $route = 'callback/RemitCallback.log';
            $wechat = \WeChat\Pay::instance(config('pay')['wechat']);
            $data = $wechat->getNotify();

            if ($data['return_code'] === 'SUCCESS' && $data['result_code'] === 'SUCCESS') {
                // @todo 更新订单状态，支付完成
                $info = \app\common\model\Remit::where(['sn' => $data['out_trade_no']])->find();
//                Logs::write($route, json_encode($info));
                if ($info) {
                    $result = \app\common\model\Remit::remit_save($info, 'wechat');
                    if ($result['code'] == 1) {
                        Logs::write($route, '成功，订单号:' . $info->sn);
                    } else {
                        Logs::write($route, '失败，订单号:' . $info->sn . '->' . $result['msg']);
                    }
                } else {
                    Logs::write($route, '未查询到订单');
                }
                return 'success';
            } else {

                // @todo 回调验证失败处理
                Logs::write($route, '回调验证失败：' . json_encode($data));
            }
            return $wechat->getNotifySuccessReply();
        } catch (\Exception $e) {
            // @todo 异常处理
            Logs::write($route, $e->getMessage());

        }
    }



    /**
     * @return string
     * 原点 2022年1月11日11:32:49 微信支付通用回调
     */
    public function wechatCallback()
    {
        try {
            $route = 'callback/wechatCallback.log';
            $wechat = \WeChat\Pay::instance(config('pay')['wechat']);
            $data = $wechat->getNotify();

            if ($data['return_code'] === 'SUCCESS' && $data['result_code'] === 'SUCCESS') {
                // @todo 更新订单状态，支付完成
                $info = Order::where(['sn' => $data['out_trade_no']])->find();
//                Logs::write($route, json_encode($info));
                if ($info && $info->status == '待付款') {
                    $result = Order::operation($info, User::find($info->uid), 'wechat');
                    if ($result['code'] == 1) {
                        Logs::write($route, '成功，订单号:' . $info->sn);
                    } else {
                        Logs::write($route, '失败，订单号:' . $info->sn . '->' . $result['msg']);
                    }
                } else {
                    Logs::write($route, '未查询到订单');
                }
                return 'success';
            } else {
                // @todo 回调验证失败处理
                Logs::write($route, '回调验证失败：' . json_encode($data));
            }
            return $wechat->getNotifySuccessReply();
        } catch (\Exception $e) {
            // @todo 异常处理
            Logs::write($route, $e->getMessage());

        }
    }

    /**
     * 消息推送
     */
    public function checkSignature() {
        try {
            $route = 'callback/confirm_receive.log';
            if(request()->isPost()){

                $postStr = file_get_contents('php://input');
                if($postStr){
                    $postdata = json_decode($postStr,true);
                    /**
                     * 消息推送确认收货
                     */
                    if($postdata['MsgType']  == 'event' && $postdata['Event'] == 'trade_manage_order_settlement'){
                        if(!empty($postdata['confirm_receive_method'])){
                            $data['status'] = 4;
                            $data['receipt_time'] = $postdata['confirm_receive_time'];
                            Order::where('sn',$postdata['merchant_trade_no'])->update($data);
                            Logs::write($route, '确认收货时间：'.date('Y-m-d H:i:s',$postdata['confirm_receive_time']) .'订单号：'.$postdata['merchant_trade_no']);
                            exit('success');
                        }
                    }
                }

            }
            if(request()->isGet()){ 
                $signature = $_GET["signature"];
                $timestamp = $_GET["timestamp"];
                $nonce = $_GET["nonce"];
                $echostr = $_GET["echostr"];
                $token = config('pay.wechat.token');
                $tmpArr = array($token, $timestamp, $nonce);
                sort($tmpArr, SORT_STRING);
                $tmpStr = implode($tmpArr);
                $tmp = sha1($tmpStr);
                if($tmp == $signature){
                    ob_clean();
                    exit(htmlspecialchars($_GET['echostr']));
                }else{
                    return false;
                }
            }
        } catch (\Exception $e) {
            Logs::write($route, $e->getMessage());
        }
    }
}